class Solution
{
public:
    bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
    {
        vector<int> inDegrees(numCourses, 0);
        unordered_map<int, unordered_set<int>> edges;
        for (auto &edge : prerequisites)
        {
            ++inDegrees[edge[0]];
            edges[edge[1]].insert(edge[0]);
        }

        int finished = 0;
        queue<int> q;
        for (int i = 0; i < numCourses; ++i)
        {
            if (inDegrees[i] == 0)
            {
                q.push(i);
            }
        }

        while (!q.empty())
        {
            int course = q.front();
            q.pop();
            ++finished;
            for (auto &nextCourse : edges[course])
            {
                --inDegrees[nextCourse];
                if (inDegrees[nextCourse] == 0)
                {
                    q.push(nextCourse);
                }
            }
        }

        return finished == numCourses;
    }
};